//
//  NetworkTools.swift
//  武汉微博
//
//  Created by 谌桃 on 16/9/24.
//  Copyright © 2016年 ryan.chen. All rights reserved.
//

import UIKit
import AFNetworking

/// 网络请求枚举类型，Swift中的枚举可以指定不同的数据类型
enum STRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {
    
    //网络 单例
    static let sharedManager:NetworkTools = {
        
        let networkTools = NetworkTools(baseURL:nil)
        
        networkTools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return networkTools
    }()
    
    /// 封装 AFN 方法发起网络请求
    ///
    /// - parameter method:     GET / POST
    /// - parameter URLString:  URLString
    /// - parameter parameters: 参数字典
    /// - parameter finished:   完成回调(json字典)
    func request(method:STRequestMethod, URLString:String , parameters:[String:AnyObject]? , finished: ((result:[String:AnyObject]?) -> Void)){
        
        //网络成功 的回调
        let success = { (task:NSURLSessionDataTask, responseObject:AnyObject?) -> Void in
            
            guard let result = responseObject as? [String:AnyObject] else{
                
                print("数据格式错误")
                finished(result: nil)
                return
            }
            
            finished(result: result)
            print("\(result)")
        }
        
        //网络失败 的回调
        let failure = { (task: NSURLSessionDataTask?, error: NSError) -> Void in
        
            print("网络请求错误 \(error)")
            finished(result: nil)

        }
        
        if method == .GET {
        
            GET(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else{
        
            POST(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
//        GET(URLString, parameters: parameters, progress: nil, success: { (_, responseObject) -> Void in
//            
//            guard let result = responseObject as? [String:AnyObject] else{
//                
//                print("数据格式错误")
//                finished(result: nil)
//                return
//            }
//            
//            finished(result: result)
//            print("\(result)")
//            
//            
//            }) { (_, error) -> Void in
//                
//                print("网络请求错误 \(error)")
//                finished(result: nil)
//        }
    }
}
